package com.world.rickcloudendpoint.service.net.session;

import com.world.rickcloudendpoint.message.AbstractNetMessage;
import io.netty.channel.Channel;
import lombok.extern.log4j.Log4j2;

/**
 * @description: netty会话
 * @author: jlsong
 * @date: 2021/12/23 23:36:02
 * @version: 1.0
 */
@Log4j2
public abstract class NetSession implements ISession{

    protected volatile Channel channel;

    private long playerId;

    public NetSession(Channel channel) {
        this.channel = channel;
    }

    @Override
    public boolean isConnected() {
        if (channel != null){
            return channel.isActive();
        }
        return false;
    }

    @Override
    public void write(AbstractNetMessage msg) throws Exception {
        if (msg != null){
            try {
                channel.writeAndFlush(msg);
            }catch (Exception e){
                throw e;
            }
        }
    }

    @Override
    public void close(boolean immediately) {
        if (channel != null) {
            channel.close();
        }
    }


    public boolean closeOnException() {
        return true;
    }

    public long getPlayerId() {
        return playerId;
    }

    public void setPlayerId(long playerId) {
        this.playerId = playerId;
    }

    @Override
    public void write(byte[] msg) throws Exception {
        if (channel != null) {
            try {
                channel.writeAndFlush(msg);
            }catch (Exception e){
                throw e;
            }
        }
    }

    public Channel getChannel() {
        return channel;
    }

    public void setChannel(Channel channel) {
        this.channel = channel;
    }
}
